from datetime import datetime

from django.shortcuts import render

# Create your views here.
from django.views.generic import View
from django.http import JsonResponse
import json
from django.http import HttpResponse
from .models import BookInfo


"""
GET     /books/         提供所有记录
POST    /books/         新增一条记录
GET     /books/<pk>/    提供指定id的记录
PUT     /books/<pk>/    修改指定id的记录
DELETE  /books/<pk>/    删除指定id的记录

响应数据    JSON
"""

class BookAPIView(View):
    """提供制定ｉｄ的记录
    ＧＥＴ　　／ｂｏｏｋｓ／<pk>
    """
    def get(self,request,pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

    # 构造json数据
        response_book_dict = {
            'id':book.id,
            'btitle':book.btitle,
            'bpub_date':book.bpub_date,
            'bread':book.bread,
            'bcomment':book.bcomment,
            'image':book.image.url if book.image else None
        }
        # 响应json数据 200
        return JsonResponse(response_book_dict)

    def put(self,request,pk):
        """修改指定id的记录
            PUT /books/<pk>
        """
        """获取前段发送的json数据"""
        # book_dict = {'btitle':'三国演义《第二版》'}
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 判断pk是否合法
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        # 修改数据
        book.btitle = book_dict.get('btitle')
        book.save()

        # 构造json数据
        response_book_dict = {
            'id':book.id,
            'btitle':book.btitle,
            'bpub_date':book.bpub_date,
            'bcomment':book.bcomment,
            'image':book.image.url if book.image else None
        }
        # 响应json状态码200
        return JsonResponse(response_book_dict)
    def delete(self,request,pk):
        """删除指定id的记录
            DELETE /books/<pk>
        """
        # 判断pk是否合法
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        # 删除book
        book.delete()

        #响应空文档  204
        return HttpResponse(status=204)

class BooksAPIView(View):
    def get(self,request):
        """提供所有记录
            GET /books/
        """
        # 查询所有的图书信息 books= 【BookInfo】
        books = BookInfo.objects.all()

        # 构造json数据 book_dict_list = [{},{},{},{},{}]  json数据必须以{}打头  或者指定safe=False   否则会报错

        book_dict_list = []
        for book in books:
            book_dict_list.append({
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment,
                'image': book.image.url if book.image else None
            })
        books_dict = {
            'books': book_dict_list
        }
        # 返回响应json
        return JsonResponse(books_dict)


    def post(self,request):
        """新增一条记录
            POST  /books/
            返回新生成的资源对象
        """
        # 获取前端发送的json数据
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 同步到数据库
        book = BookInfo.objects.create(
            btitle=book_dict['btitle'],
            bpub_date=datetime.strptime(book_dict['bpub_date'],'%Y-%m-%d'),
            bread=book_dict['bread'],
            bcomment=book_dict['bcomment']
        )
        # 构造响应字典
        response_book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }
        # 响应json数据 201
        return JsonResponse(response_book_dict,status=201)





















































































